package com.intelligentmeterreadingsys.report.activity;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.EngineeringOrderPoVo;
import com.intelligentmeterreadingsys.report.db.ReportDao;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.util.SafetyExitUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 工程单一键上传
 * @author king
 *
 */
public class ReportUploadActivity extends Activity{
	
     public Button button;//上传按钮
	 
	 public TextView textview1;//需上传总数
	 
	 public TextView textview2;//未上传总数
	 
	 public TextView textview3;//进度条描述
	 
	 public ProgressBar pb;//进度条
	 
	 public ReportDao dao;
	 
	 public TextView textview4;
	 
	 public List<EngineeringOrderPoVo> list;
	 
	 public boolean isstop=false;
	 
	 public int total=0;
	 
	 public SafetyExitUtil safe=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.waterbanding_onetoupload);
		init();
	}
    
	/**
	 * 初始化控件
	 */
   public void init(){
	   button=(Button)findViewById(R.id.waterbanding_upload_button);
	   pb=(ProgressBar)findViewById(R.id.waterbanding_progressBar);
	   textview1=(TextView)findViewById(R.id.waterbanding_upload_total);
	   textview2=(TextView)findViewById(R.id.waterbanding_noupload_total);
	   textview3=(TextView)findViewById(R.id.waterbanding_pb_textview);
	   textview4=(TextView)findViewById(R.id.onekeyupload_info);
	   textview4.setText("工程单一键上传");
	   dao=new ReportDao(this);
	   textview1.setText(dao.queryOrderTotal()+"");
	   textview2.setText(dao.queryOrderUpload()+"");
	   this.list=dao.queryUpload(null);
	   dao.close();
	   button.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
		 	
		 	 if(list==null||list.size()<1){
		 		 Toast.makeText(ReportUploadActivity.this, "没有可上传的数据!", Toast.LENGTH_LONG).show();
		 		 return;
		 	 }
		 	    ReportDao dao=new ReportDao(ReportUploadActivity.this);
		 	   if( dao.queryOrderUpload()<=0){
		 		   Toast.makeText(ReportUploadActivity.this, "没有上传的数据了！", 1000).show();
		 		   return;
		 	   }
		 	    list=dao.queryUpload(null);
		 	    dao.close();
		 		pb.setMax(list.size());
		 		textview3.setText("正在上传中....0%");
		 		new Thread(){


		 			@Override
		 			public void run() {
		 				
		 				RequestUrl r=new RequestUrl(ReportUploadActivity.this);
		 				SharedPreferenceUtil sh=new SharedPreferenceUtil(ReportUploadActivity.this);
		 				String url=r.getUrl(RequestUrl.UploadOrder);
                    
 			        	for(int i=0;i<list.size();i++){
 			        		EngineeringOrderPoVo e=list.get(i);
 			        	    Map<String, String> param=new HashMap<String, String>();
 			        	   Map<String, String> map3=new HashMap<String, String>();
 							map3.put("desc", e.getDesc());
 							map3.put("typeid", e.getTypenumber());
 							map3.put("waternumber", e.getWaternumber());
 							map3.put("name", e.getName());
 							
 							
 							map3.put("imsi",sh.getValue(XmlNameHelper.IMSI));
 			        	  
 			        	    
 			        	    Map<File, String> fileparam=new HashMap<File, String>();
 			        	     
 			        	    List<String> img=e.getImagepath();
 			        	  
 			        	    if(img!=null&&img.size()>0){
 			        	    	 for(int k=0;k<img.size();k++){
 			 	        	    	File files=new File(img.get(k));
 			 	        	    	if(files.exists()){
 			 	        	    		fileparam.put(files, "imagepath");
 			 	        	    		param.put(files.getName(), "imagename");		 			 	        	    	
 			 	        	    		
 			 	        	    	}
 			 	        	    }
 			        	    }
 			        	   
 			        	    if(e.getVideopath()!=null&&!TextUtils.isEmpty(e.getVideopath())){
 			        	    	File videofile=new File(e.getVideopath());
 				        	      if(videofile.exists()){
 				        	    	  fileparam.put(videofile ,"videopath");
 				        	    	  param.put(videofile.getName(), "videoname");
 				        	    	  
 				        	      }
 			        	    }
 			        	      
 			        	    if(e.getSoundpath()!=null&&!TextUtils.isEmpty(e.getSoundpath())){
 			        	    	File soundfile=new File(e.getSoundpath());
 				        	      if(soundfile.exists()){
 				        	    	  fileparam.put(soundfile, "soundpath");
 				        	    	  param.put(soundfile.getName(), "soundname");
 				        	      }
 			        	    }
 			        	      
 			        	      
 			        	  String respon= UploadHttpClient.uploadSubmit(url, param, fileparam,map3);  
 			        	   if(respon.equals("error")){
 			        		   
 			        		   Message msg=MyHandle.obtainMessage();
 			        		   msg.what=0;
 			        		   MyHandle.sendMessage(msg);
 			        		   return;
 			        	   }else{
 			        		   try {
								JSONObject json=new JSONObject(respon);
								String message=json.getString("message");
								if(message.equals("yes")){		 			        		   		 			        		   
		 			        		  if(i==(list.size()-1)){				 			        		
			 			        		   Message msg=MyHandle.obtainMessage();
			 			        		   msg.what=1;
			 			        		   MyHandle.sendMessage(msg);
			 			        		   return;
			 			        	   }else {
			 			        		   
			 			        		   Message msg=MyHandle.obtainMessage();
			 			        		   msg.what=2;
			 			        		   msg.arg1=i+1;
			 			        		   MyHandle.sendMessage(msg);			 			        		   
			 			        	   }
		 			        	   
								}else{
									  Message msg=MyHandle.obtainMessage();
		 			        		   msg.what=0;
		 			        		   MyHandle.sendMessage(msg);
									return;
								}
							} catch (JSONException e1) {
								 Message msg=MyHandle.obtainMessage();
	 			        		   msg.what=0;
	 			        		   MyHandle.sendMessage(msg);
								return;
								
							}
 			        		   
 			        	   }
 			        	   
 			        	}
 			        
		 				
		 			}
		 			   
		 		   
		 		}.start();
			
		}
	});
	   
   }

   
   
   
   /**
    * 消息处理
    */
   Handler MyHandle=new Handler(){

	@Override
	public void handleMessage(Message msg) {
		
		if(msg.what==0){
			pb.setProgress(0);
			textview3.setText("正在上传中.....0%");
			Toast.makeText(ReportUploadActivity.this, "网络连接错误！", Toast.LENGTH_LONG).show();
			
		}else if(msg.what==1){
			pb.setProgress(list.size());
			textview3.setText("上传完毕100%");
			Toast.makeText(ReportUploadActivity.this, "上传成功！", Toast.LENGTH_LONG).show();
			ReportDao dao=new ReportDao(ReportUploadActivity.this);
			dao.delectAll(DbTableName.ENGINEERINGORDER);
			textview1.setText("0");
			textview2.setText("0");
			
			dao.close();
			FileNameUtil f=new FileNameUtil(ReportUploadActivity.this);
			f.delectFile("OrderImage");
			f.delectFile("sound");
			f.delectFile("video");
			
		}else if(msg.what==2){
			System.out.println(msg.arg1/list.size()*100+"%");
			textview3.setText("正在上传中....."+((float)msg.arg1)/list.size()*100+"%");
			pb.setProgress(msg.arg1);
			
		}
		super.handleMessage(msg);
	}
	   
   };


@Override
protected void onDestroy() {
	if(dao!=null){
		dao.close();
	}
	super.onDestroy();
}
   
@Override
protected void onPause() {
	safe=new SafetyExitUtil(ReportUploadActivity.this);
	safe.start();	
	super.onPause();
}

@Override
protected void onResume() {
   if(safe!=null){
	   safe.stop();
   }
	super.onResume();
}
}
